import React from 'react'
import { connect } from 'react-redux'
import { Link } from 'react-router'

import Menu from '../common/Menu'
import Footer from '../common/Footer'

import LayoutComponent from '../LayoutComponent'

import {getConfig, changeBanner, changeCurrentIndex, changeHistory, changeAddStatus, addHistory, uploadImg, saveData, changeExportStatus} from '../../actions/banneraction';

class Banner extends LayoutComponent {
	constructor(props){
		super(props);
	}

	componentDidMount() {
	  	this.props.init();
	}



	render() {

		const {history, currentIndex, addStatus, selectHistory, deleteHistory, changeRecordStatus} = this.props

		// history.map((item)=>{
		// 	var img = item.pcImg;
		// 	item.pcImg = require(img);
		// })
		return (
			<div style={{background: '#222d32'}}>

				<Menu parent="gw" active="/banner"/>

				<div className="content-wrapper">

					<section className="content-header">

						<h1>
							更换首页Banner图和跳转链接
						</h1>

						<ol className="breadcrumb">

							<li>
								<Link to="/">
									<i className="fa fa-dashboard">
									</i> Home
								</Link>
							</li>

							<li className="active">Banner</li>

						</ol>

					</section>


					<section className="content">

						<h4>
							历史记录
						</h4>
						{history.map((item, index) =>
	                        <div className="" key={index}>
	                        	<label>
	                        		<input type="radio" name="desc" style={{width: '40px', height: '14px', lineHeight: '40px', display: 'inline-block', textAlign: 'left', margin: '0px', verticalAlign: 'middle'}} checked={currentIndex === index} value={item.desc} onChange={selectHistory.bind(this, currentIndex, index)} />
	                        		<span style={{width: '90px', display: 'inline-block', textAlign: 'left'}}>标题：</span>{item.desc}
	                        	</label>
	                        	<span style={{display: 'inline-block', marginLeft: '20px'}}>
	                        		{currentIndex === index ? 
	                        			''
	                        			:
	                        			<button onClick={deleteHistory.bind(this, history, currentIndex, index)}>删除此记录</button>
	                        		}
	                        	</span><br />
	                        	<span style={{width: '90px', display: 'inline-block', textAlign: 'left', marginLeft: '40px'}}>PC端链接：</span>{item.pcUrl}<br /><br />
								<span style={{width: '90px', display: 'inline-block', textAlign: 'left', marginLeft: '40px'}}>移动端链接：</span>{item.mobileUrl}<br /><br />
								<span style={{width: '90px', display: 'inline-block', textAlign: 'left', marginLeft: '40px'}}>PC端图片：</span>{'http://10.10.32.53:8765/config/' + item.pcImg}<br /><br />
								<span style={{width: '90px', display: 'inline-block', textAlign: 'left', marginLeft: '40px'}}>移动端图片：</span>{'http://10.10.32.53:8765/config/' + item.mobileImg}<br /><br />
	                        </div>
	                        )
	                    }

	                    {addStatus ? 
		                    <div style={{borderTop: 'solid 1px #ccc', padding: '10px 0', marginTop: '20px'}}>
			                    <h4>新增数据</h4>
		                    	<span style={{width: '90px', display: 'inline-block', textAlign: 'right'}}>标题：</span>
		                    	<input style={{width: '500px', padding: '2px'}} className="" type="text" placeholder="请输入标题" ref="desc_title" /><br /><br />

								<span style={{width: '90px', display: 'inline-block', textAlign: 'right'}}>PC端链接：</span>
								<input style={{width: '500px', padding: '2px'}} className="" type="text" placeholder="请输入PC端跳转链接" ref="pc_url" /><br /><br />

								<span style={{width: '90px', display: 'inline-block', textAlign: 'right'}}>移动端链接：</span>
								<input style={{width: '500px', padding: '2px'}} className="" type="text" placeholder="请输入移动端跳转链接" ref="mobile_url" /><br /><br />

								<span style={{width: '90px', display: 'inline-block', textAlign: 'right'}}>PC端图片：</span>
								<input style={{width: '456px', display: 'inline-block'}} type="file" accept="image/jpeg,image/png" ref="pc_img" onChange={this.changePcImg.bind(this)} />
								<button style={{marginLeft: '0px'}} onClick={this.uploadPcImg.bind(this)}>上传</button><br /><br />
								<img src="" ref="pc_img_view" style={{marginLeft: '90px', display: 'inline-block', width: '500px', height : '281px'}} /><br /><br />

								<span style={{width: '90px', display: 'inline-block', textAlign: 'right'}}>移动端图片：</span>
								
								<input style={{width: '456px', display: 'inline-block'}} type="file" accept="image/jpeg,image/png" ref="mobile_img" onChange={this.changeMobileImg.bind(this)} />
								<button style={{marginLeft: '0px'}} onClick={this.uploadMobileImg.bind(this)}>上传</button><br /><br />
								<img src="" ref="mobile_img_view" style={{marginLeft: '90px', display: 'inline-block', width: '320px', height : '375px'}} /><br /><br />

								<span style={{width: '90px', display: 'inline-block', textAlign: 'right'}}>&nbsp;</span>
								<button onClick={this.saveNew.bind(this)}>保存新增</button>
								<button style={{marginLeft: '40px'}} onClick={this.cancelNew.bind(this)}>取消新增</button><br />

		                    </div>
		                    :
		                    <div style={{borderTop: 'solid 1px #ccc', padding: '10px 0', marginTop: '20px'}}>
		                    	<span style={{width: '90px', display: 'inline-block', textAlign: 'right'}}>&nbsp;</span>
		                    	<button onClick={changeRecordStatus.bind(this, true)}>新增数据</button>
		                    </div>
	                    }


	                    <div style={{borderTop: 'solid 1px #ccc', padding: '10px 0', marginTop: '150px'}}>
	                    	<span style={{width: '90px', display: 'inline-block', textAlign: 'right'}}>&nbsp;</span>
							<button onClick={this.saveModified.bind(this)}>保存所有变更</button><br />
						</div>
						

					</section>
				</div>

				<Footer/>

			</div>
		)
	}

	saveNew () {
		const { saveNew, history } = this.props

		var item = {
			desc : this.refs.desc_title.value.trim(),
			pcUrl : this.refs.pc_url.value.trim(),
			mobileUrl : this.refs.mobile_url.value.trim(),
			pcImg : this.refs.pc_img.getAttribute('imgname'),
			mobileImg : this.refs.mobile_img.getAttribute('imgname')
		}

		if(!item.desc){
			alert('请输入标题');
			return;
		}
		if(!item.pcUrl){
			alert('请输入PC端跳转链接');
			return;
		}
		if(!item.mobileUrl){
			alert('请输入移动端跳转链接');
			return;
		}
		if(!item.pcImg){
			alert('请上传PC端图片');
			return;
		}
		if(!item.mobileImg){
			alert('请上传移动端图片地址');
			return;
		}

		saveNew(item, history);
		alert('新增的数据保存成功');
	}


	cancelNew () {
		const { changeRecordStatus } = this.props
		if(confirm("您确定取消新增的数据吗？")){
			changeRecordStatus(false);
		}
	}

	changePcImg () {

		this.refs.pc_img.setAttribute('imgname', '');

		if(this.refs.pc_img.files[0]){
			var reader = new FileReader();
			var self = this;
			reader.onload = function(e){
				self.refs.pc_img_view.src = e.target.result;
			}
			reader.readAsDataURL(this.refs.pc_img.files[0]);
		}else{
			this.refs.pc_img_view.src = '';
		}
	}

	changeMobileImg () {

		this.refs.mobile_img.setAttribute('imgname', '');

		if(this.refs.mobile_img.files[0]){
			var self = this;
			var reader = new FileReader();
			reader.onload = function(e){
				self.refs.mobile_img_view.src = e.target.result;
			}
			reader.readAsDataURL(this.refs.mobile_img.files[0]);
		}else{
			this.refs.mobile_img_view.src = '';
		}
	}

	uploadPcImg () {
		const { saveImg } = this.props

		if(this.refs.pc_img.files[0]){
			if(!this.refs.pc_img.getAttribute('imgname')){
				var self = this,
					nameArr = this.refs.pc_img.files[0].name.split('.'),
					name = new Date().getTime() + '.' + nameArr[nameArr.length - 1];

				saveImg(this.refs.pc_img.files[0], name, function(){
					self.refs.pc_img.setAttribute('imgname', name);
					alert('图片上传成功');
				});
			}else{
				alert('该图片已经上传过了');
			}
		}else{
			alert('请先选择图片');
		}
	}

	uploadMobileImg () {
		const { saveImg } = this.props

		if(this.refs.mobile_img.files[0]){
			if(!this.refs.mobile_img.getAttribute('imgname')){
				var self = this,
					nameArr = this.refs.mobile_img.files[0].name.split('.'),
					name = new Date().getTime() + '.' + nameArr[nameArr.length - 1];

				saveImg(this.refs.mobile_img.files[0], name, function(){
					self.refs.mobile_img.setAttribute('imgname', name);
					alert('图片上传成功');
				});
			}else{
				alert('该图片已经上传过了');
			}
		}else{
			alert('请先选择图片');
		}
	}

	saveModified () {
		const { addStatus, history, currentIndex, originalPrice, discountPrice, saveModified } = this.props

		if(addStatus){
			alert('请先保存新增数据，或取消新增数据');
		}else{
			var saveObj = {
				history : history,
				currentIndex : currentIndex,
				originalPrice : originalPrice,
				discountPrice : discountPrice
			}
			saveModified(saveObj, function(){
				alert('数据保存成功');
			});
		}
	}

}

//使用connect创建component，把dispatch和state传进ui component
export default connect(
	(state)=>({
		history : state.bannerReducer.history,
		currentIndex : state.bannerReducer.currentIndex,
		addStatus : state.bannerReducer.addStatus,
		originalPrice : state.priceReducer.originalPrice,
		discountPrice : state.priceReducer.discountPrice
	}),

	(dispatch)=>({

		init:() => {
			dispatch(getConfig());
		},

		selectHistory : (currentIndex, index) => {
			if(currentIndex !== index){
				dispatch(changeCurrentIndex(index));
				dispatch(changeExportStatus(false));
			}
        },

        deleteHistory : (history, currentIndex, index) => {
        	var sure = confirm("您确定删除此记录吗？");
  			if (sure){
	        	if(currentIndex === index){
	        		dispatch(changeCurrentIndex(null));
	        	}else if(currentIndex > index){
	        		dispatch(changeCurrentIndex(currentIndex - 1));
	        	}
	        	var newHistory = [];
	        	for(var i = 0, len = history.length; i < len; i++){
	        		if(i !== index){
	        			newHistory.push(history[i]);
	        		}
	        	}
				dispatch(changeHistory(newHistory));
				dispatch(changeExportStatus(false));
			}
        },

        saveImg : (imgElem, name, cb) => {
        	dispatch(uploadImg(imgElem, name, cb));
        },

        changeRecordStatus : (addStatus) => {
			dispatch(changeAddStatus(addStatus));
        },

        saveNew: (historyItem, history) => {
        	var len = history.length;
			dispatch(addHistory(historyItem));
			dispatch(changeCurrentIndex(len));
			dispatch(changeAddStatus(false));
			dispatch(changeExportStatus(false));
        },

        saveModified : (data, cb) => {
        	dispatch(saveData(data, cb));
        },
	})
)(Banner)
